package com.oweight.sagacious.auth.server.interfaces.controller;

import com.oweight.sagacious.auth.server.application.IClientApplication;
import com.oweight.sagacious.auth.server.domain.entity.Client;
import com.oweight.sagacious.auth.server.domain.service.IClientServiceManager;
import com.oweight.sagacious.auth.server.infrastructure.configuration.KeyConfiguration;
import com.oweight.sagacious.api.model.msg.Message;
import com.oweight.sagacious.common.interfaces.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 客户端：Controller
 *
 * @author SAGE
 * @version v1 2019-10-21 09:47:00
 */
@Slf4j
@RestController
@RequestMapping("/client")
public class ClientController extends BaseController<Client, IClientApplication> {

    @Autowired
    private IClientServiceManager authClientService;

    @Autowired
    private KeyConfiguration keyConfiguration;

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public Message getAccessToken(String clientId, String secret) throws Exception {
        return getMessage().data(authClientService.apply(clientId, secret));
    }

    @RequestMapping(value = "/myClient")
    public Message getAllowedClient(String serviceId, String secret) {
        return getMessage().data(authClientService.getAllowedClient(serviceId, secret));
    }

    /**
     * 客户端获取服务端生成的公钥
     *
     * @param clientId
     * @param secret
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/servicePubKey", method = RequestMethod.POST)
    public byte[] getServicePublicKey(@RequestParam("clientId") String clientId, @RequestParam("secret") String secret) throws Exception {
        authClientService.validate(clientId, secret);
        return keyConfiguration.getServicePubKey();
    }

    @RequestMapping(value = "/userPubKey", method = RequestMethod.POST)
    public byte[] getUserPublicKey(@RequestParam("clientId") String clientId, @RequestParam("secret") String secret) throws Exception {
        authClientService.validate(clientId, secret);
        return keyConfiguration.getUserPubKey();
    }
}
